package com.shycloud.mido.member.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.member.api.entity.SmCourseware;
import com.shycloud.mido.member.api.entity.SmCoursewareFolder;
import com.shycloud.mido.member.api.entity.SmCoursewareFolderCourseware;
import com.shycloud.mido.member.api.vo.SmCoursewareVO;
import com.shycloud.mido.member.mapper.SmCoursewareFolderCoursewareMapper;
import com.shycloud.mido.member.mapper.SmCoursewareGroupFolderMapper;
import com.shycloud.mido.member.mapper.SmCoursewareMapper;
import com.shycloud.mido.member.service.SmCoursewareService;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;

@Service
@AllArgsConstructor
public class SmCoursewareServiceImpl extends ServiceImpl<SmCoursewareMapper, SmCourseware> implements SmCoursewareService {

	/** 七牛云上传 */
	private MinioTemplate minioTemplate;
	/** 课件文件 mapper */
	private SmCoursewareMapper coursewareMapper;
	/** 课件文件夹与课件文件关系模块 mapper */
	private SmCoursewareFolderCoursewareMapper folderCoursewareMapper;
	/** 课件分组与课件文件夹模块 mapper */
	private SmCoursewareGroupFolderMapper groupFolderMapper;

	/**
	 * 添加课件文件
	 *
	 * @param file
	 * @param type
	 * @param folderId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/10/13 10:10
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public SmCourseware addCourseware(MultipartFile file, String type, Integer folderId, Integer musicId) {

		//添加曲目文件时判断曲目文件是否重复
		if ("1".equals(type)) {

			List<SmCourseware> courseware = coursewareMapper.selectList(new QueryWrapper<SmCourseware>()
					.eq(SmCourseware.COL_MUSIC_ID, musicId));

			//判断曲目是否在同一个文件夹下，如果在的话才报错，不在则不报错
			for (SmCourseware smCourseware : courseware) {
				List<SmCoursewareFolderCourseware> folderList = folderCoursewareMapper.selectList(new QueryWrapper<SmCoursewareFolderCourseware>()
						.eq(SmCoursewareFolderCourseware.COL_FOLDER_ID, folderId)
						.eq(SmCoursewareFolderCourseware.COL_COURSEWARE_ID, smCourseware.getId()));
				if (folderList.size() > 0) {
					throw new BusinessException("该曲目已在列表中，无需重复添加");
				}
			}
		}

		String musicName = coursewareMapper.getMusicNameById(musicId);
		//课件名称
		String coursewareName = musicName;
		//课件上传路径
		String url = StringUtils.EMPTY;

		if (file != null && !StringUtils.EMPTY.equals(file.getOriginalFilename())) {

			//提取文件名
			String fileName = file.getOriginalFilename().replaceAll(" ", "");

			if (fileName.contains(".")) {
				String filedNameBefore = fileName.substring(0, fileName.lastIndexOf("."));
				coursewareName = filedNameBefore;
			} else {
				coursewareName = fileName;
			}

			//后缀
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			String uuid = UUID.randomUUID().toString();
			//提取上传文件名称
			String uploadFileName = uuid.replace("-", "") + "." + suffix;

			//判断是否上传过相同文件
			List<SmCourseware> smCoursewares = coursewareMapper.selectList(new QueryWrapper<SmCourseware>().eq(SmCourseware.COL_NAME, coursewareName));
			if (smCoursewares.size() > 0) {
				coursewareName = coursewareName + (smCoursewares.size() + 1);
			}

			try {
				//上传课件
				minioTemplate.uploadFile(file.getInputStream(), uploadFileName, "zebra-courseware");
			} catch (IOException e) {
				throw new BusinessException(e.getLocalizedMessage());
			}

			url = "http://courseware.joymido.com/" + uploadFileName;
		}

		//添加课件
		SmCourseware courseware = new SmCourseware();
		//课件名称
		courseware.setName(coursewareName);
		//类型： 1.曲目 2.视频 3.图片
		courseware.setType(type);
		//文件路径
		if ("1".equals(type)) {
			courseware.setMusicId(musicId);
		}
		if ("2".equals(type)) {
			courseware.setMp4Url(url);
		}
		if ("3".equals(type)) {
			courseware.setImgUrl(url);
		}
		coursewareMapper.insert(courseware);

		//添加文件夹-课件关系信息
		SmCoursewareFolderCourseware folderCourseware = new SmCoursewareFolderCourseware();
		//文件夹ID
		folderCourseware.setFolderId(folderId);
		//课件ID
		folderCourseware.setCoursewareId(courseware.getId());
		folderCoursewareMapper.insert(folderCourseware);

		return courseware;
	}

	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public String uploadFile(MultipartFile file) {

		//文件上传路径
		String url = StringUtils.EMPTY;

		if (!StringUtils.EMPTY.equals(file.getOriginalFilename())) {

			//提取文件名
			String fileName = file.getOriginalFilename().replaceAll(" ", "");
			//后缀
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			String uuid = UUID.randomUUID().toString();
			//提取上传文件名称
			String uploadFileName = uuid.replace("-", "") + "." + suffix;

			try {
				//上传课件
				minioTemplate.uploadFile(file.getInputStream(), uploadFileName, "zebra-courseware");
			} catch (IOException e) {
				throw new BusinessException(e.getLocalizedMessage());
			}

			url = "http://courseware.joymido.com/" + uploadFileName;
		}
		return url;
	}

	/**
	 * 获取课件列表
	 *
	 * @param page
	 * @param folderId
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.member.api.entity.SmCourseware>
	 * @author nianhua.jiang
	 * @date 2020/10/13 13:44
	 **/
	@Override
	public IPage<SmCoursewareVO> getCoursewareList(Page page, Integer folderId) {
		return coursewareMapper.getCoursewareList(page, folderId);
	}

	/**
	 * 删除课件
	 *
	 * @param ids
	 * @param folderId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/10/13 14:45
	 **/
	@Override
	@SneakyThrows
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean delCourseware(Integer folderId, List<Integer> ids) {

		//删除文件夹-课件关系信息
		for (Integer id : ids) {
			folderCoursewareMapper.delete(new QueryWrapper<SmCoursewareFolderCourseware>()
					.eq(SmCoursewareFolderCourseware.COL_COURSEWARE_ID, id)
					.eq(SmCoursewareFolderCourseware.COL_FOLDER_ID, folderId));

			//删除七牛云文件
			SmCourseware folderCourseware = coursewareMapper.selectById(id);

			//删除课件信息
			coursewareMapper.deleteById(id);

			// 类型： 1.曲目  2.视频 3.图片
			if ("2".equals(folderCourseware.getType())) {
				minioTemplate.removeObject("zebra-courseware", folderCourseware.getMp4Url().substring(30));
			}

			if ("3".equals(folderCourseware.getType())) {
				minioTemplate.removeObject("zebra-courseware", folderCourseware.getImgUrl().substring(30));
			}

		}
		return true;
	}

	@Override
	public IPage<SmCoursewareFolder> getFolderList(Page page, Integer groupId) {

		if (groupId == -1) {
			return groupFolderMapper.getFolderListAll(page, SecurityUtils.getMember().getId());
		}

		return groupFolderMapper.getFolderList(page, groupId);
	}
}

